<?php
class CALIX_Model extends CI_Model
{
	private $_attributes;
	public $dao;
	public $tableName;
	
	public $isNewRecord;
	
	private $_fields;
	private $_pk;
	
	
	public function init()
	{
		$CI = &get_instance();
		$CI->load->database('',FALSE,TRUE);
		$this->dao = $CI->db;
		$this->_initFields();
	}
	
	private function _initFields()
	{
		$field_data = $this->dao->field_data($this->tableName);
		if(!empty($field_data)){
			foreach($field_data as $field)
			{
				$this->_fields[$field->name] = $field;
				if($field->primary_key == 1){
					$this->_pk [] = $field->name;
				}
			}
		}
	}
	
	public function getFields()
	{
		return $this->_fields;
	}
	
	public function getPk()
	{
		return $this->_pk;
	}
	
	

	public function __get($key)
	{
		if(isset($this->_attributes[$key])){
			return $this->_attributes[$key];
		}
		return parent::__get($key);
	}
	
	
	public function __set($key,$value)
	{
		if($key == 'attributes' && is_array($value)){
			foreach($value as $k => $v){
				if(isset($this->_fields[$k])){
					$this->_attributes[$k] = $v;
				}
			}
		}else{
			if(isset($this->_fields[$key])){
				$this->_attributes[$key] = $value;
			}
		}	
	}
	
	public function save()
	{
		$this->dao->insert($this->tableName,$this->_attributes);
	}
	
	public function find($pk)
	{
		if(is_array($pk)  && count($this->_pk) > 1){
			$condition = array();
			foreach($pk as $k => $v)
			{
				if(in_array($k,$this->_pk)){
					$condition[$k] = $v;
				}
			}
		}elseif(!is_array($pk) && count($this->_pk) == 1){
			$condition[$this->_pk[0]] = $pk;
		}else{
			return NULL;
		}
		
		$query = $this->dao->where($condition)->get($this->tableName,1);
		if($query->num_rows()>0){
			$records = $query->result_array();
			return $this->_buildActiveRecord($records[0]);
		}else{
			return NULL;
		}
	}
	
	private function _buildActiveRecord($data)
	{
		$class = get_class($this);
		$ar = new $class();
		$ar->init();
		$ar->attributes = $data;
		$ar->isNewRecord = false;
		return $ar;
	}
}